local _M = { _VERSION = "0.1" }

function _M.get_payment_channel(payment_channel_policy, invalid_payment_channel, assigned_market)

  if (not payment_channel_policy) then
   return ""
  end

  if (not invalid_payment_channel) then
    invalid_payment_channel = {}
  end

  -- when assigned_market not empty and not in at invalid_payment_channel then return assigned_market
  do
    if assigned_market and assigned_market ~= "" then
      local flag = true
      for _, v in ipairs(invalid_payment_channel) do
        if v == assigned_market then
          flag = false
        end
      end
      if flag then
        return assigned_market
      end
    end
  end


  local payment_channel = ""
  local payment_channel_pool
  local payment_channel_size
  do
    local _map = {}
    local _max = 0
    -- remove invalid_payment_channel
    for _, v in ipairs(invalid_payment_channel) do
      for k, vv in ipairs(payment_channel_policy) do
       if v == vv.market then
          table.remove(payment_channel_policy, k)
       end
      end
    end
    table.sort(payment_channel_policy, function(a, b) return a.weight < b.weight end)

    -- gen payment channel pool
    for k, v in ipairs(payment_channel_policy) do
      if v.weight > 0 then
        _map[k] = {
          market = v.market,
          max    = _max + v.weight,
        }
        _max = _max + v.weight
      end
    end
    table.sort(_map, function(a, b) return a.max > b.max end)

    -- export
    payment_channel_size = _max
    payment_channel_pool = _map
  end

  -- random get payment channel
  do
    -- reset payment channel
    payment_channel = ""
    math.randomseed(tonumber(tostring(ngx.now() * 1000):reverse():sub(1, 9)))
    local num = math.random(1, payment_channel_size)

    for _, v in ipairs(payment_channel_pool) do
      if num <= v.max then
        payment_channel = v.market
      end
    end
  end

  return payment_channel
end


return _M